/*
 * Professional Android, 4th Edition
 * Reto Meier and Ian Lake
 * Copyright 2018 John Wiley Wiley & Sons, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.professionalandroid.apps.earthquake;

import android.app.Application;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.os.CancellationSignal;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

/**
 * 10.1 为SearchView生成搜索建议
 */
public class EarthquakeSearchProviderwxz extends ContentProvider {

  /**
   * 搜索建议Tag
   */
  private static final int SEARCH_SUGGESTIONS = 10086;
  private static final String ParamAuthority = "com.professionalandroid.provider.earthquakewxz";
  /**
   * 10.2 分配UriMatcher对象，识别搜索请求。Allocate the UriMatcher object, recognize search requests.
   * 由于此ContentProvider专门用于搜索建议，因此只需包含这些查询类型的匹配项即可
   */
  private static final UriMatcher uriMatcher;
  static {
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    uriMatcher.addURI(ParamAuthority, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGESTIONS);
    uriMatcher.addURI(ParamAuthority,SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGESTIONS);
    uriMatcher.addURI(ParamAuthority,SearchManager.SUGGEST_URI_PATH_SHORTCUT, SEARCH_SUGGESTIONS);
    uriMatcher.addURI(ParamAuthority,SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", SEARCH_SUGGESTIONS);
  }

  /**
   * 10.4 通过RoomDatabase执行搜索，而不是直接访问SQLite数据库，确认可以在onCreate方法中访问并返回true
   * @return
   */
  @Override
  public boolean onCreate() {
    EarthquakeDatabaseAccessor.getInstance(getContext().getApplicationContext());
    return true;
  }

  /**
   * 返回查询的搜索建议
   * 10.7 实现查询方法，检查接收到的URI是否是搜索建议请求的形式，如果是，使用当前部分查询的方法查询Room数据库
   * @param uri 通过uri.getLastPathSegment()获取查询的关键词
   * *uri要查询的uri。这将是客户端发送的完整URI；
   * *如果客户端正在请求特定记录，URI将以记录编号结尾 实现应该解析并添加到WHERE或HAVING子句，指定 这个_id值。
   * @param projection 投影
   * projection要放入Cursor的列列表。如果 {@code null}包含所有列。
   * @param selection 选择
   * selection筛选行时要应用的选择条件。 如果{@code null}，则包括所有行
   * @param selectionArgs 选择参数
   * SelectionAgs您可以在选择中包括？s，它将被替换为 SelectionAgs中的值，以便它们出现在所选内容中。
   * *这些值将被绑定为字符串。
   * @param sortOrder 排序
   * 如何对Cursor中的行进行排序。
   * *如果{@code null}，则提供程序可以自由定义排序顺序。
   * @return a Cursor or {@code null}.
   */
  @Nullable
  @Override
  public Cursor query(@NonNull Uri uri, @Nullable String[] projection,
                      @Nullable String selection,
                      @Nullable String[] selectionArgs,
                      @Nullable String sortOrder) {
    if (uriMatcher.match(uri) == SEARCH_SUGGESTIONS) {
      String searchQuery = "%" + uri.getLastPathSegment() + "%";
      EarthquakeDAO earthquakeDAO
        = EarthquakeDatabaseAccessor
            .getInstance(getContext().getApplicationContext())
            .earthquakeDAO();
      Cursor c = earthquakeDAO.generateSearchSuggestions(searchQuery);

      // Return a cursor of search suggestions.
      return c;
    }
    return null;
  }
  @Nullable
  @Override
  public Cursor query(@NonNull Uri uri, @Nullable String[] projection,
                      @Nullable String selection,
                      @Nullable String[] selectionArgs,
                      @Nullable String sortOrder,
                      @Nullable   CancellationSignal cancellationSignal ) {
    return query(  uri,  projection, selection, selectionArgs,  sortOrder );
  }
  /**
   * 10.3 重写该方法，返回搜索建议的MINE类型
   * @param uri
   * @return
   */
  @Nullable
  @Override
  public String getType(@NonNull Uri uri) {
    switch (uriMatcher.match(uri)) {
      case SEARCH_SUGGESTIONS:
        return SearchManager.SUGGEST_MIME_TYPE;
      default:
        throw new IllegalArgumentException("Unsupported URI: " + uri);
    }
  }

  @Nullable
  @Override
  public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
    return null;
  }

  @Override
  public int delete(@NonNull Uri uri, @Nullable String selection,
                    @Nullable String[] selectionArgs) {
    return 0;
  }

  @Override
  public int update(@NonNull Uri uri, @Nullable ContentValues values,
                    @Nullable String selection,
                    @Nullable String[] selectionArgs) {
    return 0;
  }
}